<?php

namespace XWAM\Addon\PXCallSystem\Controller;

/**
 * 用户控制器（包含管理员和座席）
 *
 * @since 1.0 <2014-6-13> sutroon Added.
 */
class AdminController extends AppbaseController {

    /**
     * 管理员列表页面
     * @since 1.0 <2014-6-13> SoChishun Added.
     * @since 2.0 <2015-6-12> SoChishun Refacting.
     */
    public function admin_list() {
        $this->display();
    }

    public function admin_edit($id = 0) {
        if ($id) {
            $data = AddonD('Admin')->find($id);
            $this->assign('data', $data);
        }
        $this->display();
    }

    public function admin_role($id) {
        $this->assign('data', AddonD('Admin')->find($id));
        $this->display();
    }

    /**
     * 获取列表查询数据
     * @return array
     * @since 1.0 <2015-7-2> SoChishun Added.
     */
    function get_admin_search_data() {
        $search = I();
        $where['userType'] = 'ADMIN';
        if ($search['createdTime']) {
            $where['createdTime'] = array('EGT', $search['createdTime']);
        }
        if (strlen($search['payType']) > 0) {
            $where['payType'] = $search['payType'];
        }
        if ($search['userName']) {
            $where['userName'] = $search['userName'];
        }
        if (!$this->isSuperAdmin) {
            $where['siteID'] = $this->loginData['siteID'];
        }
        return array('search' => $search, 'where' => $where);
    }

    /**
     * 导出数据
     * @since 1.0 <2014-6-13> SoChishun Added.
     */
    public function admin_export() {
        if (!$this->isSuperAdmin) {
            die('没有权限!');
        }
        $search_data = $this->get_admin_search_data();
        $list = AddonD('Admin')->scope('export')->where($search_data['where'])->select();
        if (!$list) {
            $this->ajaxMsg(false, '找不到符合条件的记录!');
        }
        sofn_excel_export($list);
    }

    /**
     * 获取列表JSON数据
     * @since 1.0 <2015-6-10> SoChishun Added.
     */
    public function get_admin_list_json() {
        $search_data = $this->get_admin_search_data();
        $list = AddonD('Admin')->get_admin_list($search_data['where']);
        $this->ajaxReturn($list);
    }

    /**
     * 获取可用租户ID
     * @param int $max
     * @since 1.0 <2015-6-10> SoChishun Added.
     */
    public function get_siteid_json($max = 50) {
        $skips = M('tuser_member')->distinct(true)->getField('siteID', true);
        $out = array();
        for ($i = 1; $i < $max; $i++) {
            if ($skips && in_array($i, $skips)) {
                continue;
            }
            $out[] = array('id' => $i, 'text' => $i);
        }
        $this->ajaxReturn($out);
    }

    /**
     * 获取租户列表
     */
    public function get_admin_json() {
        $arr = AddonD('Admin')->scope('idtext')->select();
        $this->ajaxReturn($arr);
    }

    public function admin_password_reset() {
        $id = I('id');
        $where['id'] = $id;
        if (!$id) {
            $this->ajaxMsg(false, '参数有误');
        }
        $result = AddonD('Admin')->update_password($where, '*' . sofunc_password('123456'));
        $this->ajaxMsg($result, '密码重置{%}');
    }

    public function user_profile() {
        if (equal_permission_name('编辑来电提醒模式',$this->loginData['role_id'])) {
            $ldtp_c2ie = false;
            $ldtp_state = true;
            $ldtp_duplicate_expire = 1800;
            $filename = $_SERVER['DOCUMENT_ROOT'] . '/LSR/Conf/amisocket_conf.php';
            if (file_exists($filename)) {
                $config = include $filename;
                $ldtp_c2ie = $config['ldtp_c2ie'];
                $ldtp_state = $config['ldtp_state'];
                if (!empty($config['ldtp_duplicate_expire'])) {
                    $ldtp_duplicate_expire = $config['ldtp_duplicate_expire'];
                }
            }
            $this->assign('ldtp_c2ie', $ldtp_c2ie);
            $this->assign('ldtp_state', $ldtp_state);
            $this->assign('ldtp_duplicate_expire', $ldtp_duplicate_expire);
            $data = M('tuser_member')->where('id=' . $this->loginData['id'])->field('sipPort, sipUserAgent, call_remainder')->find();
            if (!$data['sipPort']) {
                $data['sipPort'] = C('CTI_PORT');
            }
            if (!$data['sipUserAgent']) {
                $data['sipUserAgent'] = C('SIP_USERAGENT');
            }
            $this->assign('data', $data);
        }
        $this->display();
    }

    public function user_profile_save() {
        $id = I('id');
        if (!$id) {
            $this->ajaxMsg(false, '参数有误!');
        }
        $pwd = I('password');
        $repwd = I('repassword');
        $sipPort = I('sipPort');
        $sipPort_old = I('sipPort_old');
        $sipUserAgent = I('sipUserAgent');
        $sipUserAgent_old = I('sipUserAgent_old');
        $call_remainder = I('call_remainder');

        if ($pwd && $pwd != $repwd) {
            $this->ajaxMsg(false, '两次密码输入不一致!');
            // $this->ajaxMsg(false, '两次密码输入不一致!');
        }
        $M = M('tuser_member');
        if ($pwd && $this->loginData['userType'] !== 'SEAT') {
            $pwd = '*' . sofunc_password($pwd);
        }
        $pageSize = I('pageSize');
        if (!is_numeric($pageSize)) {
            $pageSize = C('USER.PAGE_SIZE');
        }
        $this->update_loginData(array('pageSize' => $pageSize));
        $result = M('tuser_appsetting')->where('userID=' . $id)->setField('pageSize', $pageSize);
        $data = false;
        if ($pwd) {
            $data['password'] = $pwd;
        }
        if ($sipPort && $sipPort != $sipPort_old) {
            $data['sipPort'] = $sipPort;
        }
        if ($sipUserAgent && $sipUserAgent != $sipUserAgent_old) {
            $data['sipUserAgent'] = $sipUserAgent;
        }
        if ($call_remainder) {
            $data['call_remainder'] = $call_remainder;
        }
        if ($data) {
            if (isset($data['sipPort']) || isset($data['sipUserAgent'])) {
                $sip_general_custom_path = '/etc/asterisk/sip_general_custom.conf';
                chmod($sip_general_custom_path, 0777);
                file_put_contents($sip_general_custom_path, 'useragent=' . $sipUserAgent . PHP_EOL . 'bindport=' . $sipPort);
                if (isset($data['sipPort'])) {
                    C('CTI_PORT', $sipPort);
                    M('asterisk.endpoint_global')->where("`key`='sipPort'")->setField('values', $sipPort);
                    chmod('/etc/sysconfig/iptables', 0777);
                    chmod('/etc/sysconfig/iptables.org', 0777);
                    $msg = sofn_update_iptables('udp:' . $sipPort, 'udp:' . $sipPort_old);
                    if (true !== $msg) {
                        die($msg);
                    }
                    sofn_update_iptables('udp:' . $sipPort, 'udp:' . $sipPort_old, '/etc/sysconfig/iptables.org', TRUE);
                }
            }
            $result = $M->where('id=' . $id)->save($data);
            $str = 'userid=' . $id;
            foreach ($data as $k => $v) {
                $str.=" ,$k=$v";
            }
            BaseController::add_user_event_log('密码', '[修改{%}] ' . $str, $result);
        }
        if (isset($_POST['ldtp_c2ie'])) {
            $ldtp_c2ie = I('ldtp_c2ie');
            $ldtp_state = I('ldtp_state');
            $ldtp_duplicate_expire = I('ldtp_duplicate_expire');
            $filename = $_SERVER['DOCUMENT_ROOT'] . '/LSR/Conf';
            if (!is_dir($filename)) {
                mkdir($filename, 0777, true);
            }
            $filename.='/amisocket_conf.php';
            if (file_exists($filename)) {
                $config = require $filename;
                $config['ldtp_c2ie'] = $ldtp_c2ie;
                $config['ldtp_state'] = $ldtp_state;
                $config['ldtp_duplicate_expire'] = $ldtp_duplicate_expire;
            } else {
                $config = array('ldtp_c2ie' => $ldtp_c2ie, 'ldtp_state' => $ldtp_state, 'ldtp_duplicate_expire' => $ldtp_duplicate_expire);
            }
            file_put_contents($filename, '<?php return ' . var_export($config, true) . ';');
        }
        $this->ajaxMsg($result, '保存{%}');
    }

    /**
     * 保存管理员
     * @since 1.0 <2015-6-11> SoChishun Added.
     */
    public function save_admin_json() {
        if (!$this->isSuperAdmin) {
            $this->ajaxMsg(false, '没有权限');
        }
        $msg = AddonD('Admin')->save_admin($this->loginData['id']);
        if (!$msg['status'] && is_array($msg['info'])) {
            $msg['info'] = implode("<br />", $msg['info']);
        }
        $this->ajaxReturn($msg);
    }

    /**
     * 保存管理员角色
     * @since 1.0 <2015-8-4> SoChishun Added.
     */
    public function save_admin_role() {
        if (!$this->isSuperAdmin) {
            $this->ajaxMsg(false, '没有权限');
        }
        $id = I('id');
        $role_id = I('role_id');
        if (!$id || !$role_id) {
            $this->ajaxMsg(false, '参数有误');
        }
        $result = M('tuser_member')->where(array('id' => $id))->setField('role_id', $role_id);
        $this->ajaxMsg($result);
    }

    /**
     * 同步保存用户数据
     * @param array $data
     * @return false|int
     * @since 1.0 2014-12-29 by sutroon
     */
    function synchronousSaveData($data) {
        $result = M('tuser_member')->save($data);
        if (false !== $result) {
            $result = M('tuser', '', 'DB_CONFIG_CRM')->save($data);
        }
        return $result;
    }

    /**
     * 删除管理员
     * @param string $id 主键编号,多个之间以逗号隔开
     * @since 1.0 <2015-6-10> SoChishun Added.
     */
    public function admin_delete($id = '') {
        if (!$this->isSuperAdmin) {
            $this->ajaxMsg(false, '没有权限');
        }
        if (!$id) {
            $this->ajaxMsg(false, '编号无效');
        }
        $msg = AddonD('Admin')->admin_delete($id, $this->loginData['id']);
        $this->ajaxReturn($msg);
    }

    public function admin_recharge() {
        if (!$this->isSuperAdmin) {
            die('没有权限!');
        }
        $id = I('id');
        if (!$id) {
            $this->ajaxMsg(false, '编号有误!');
        }
        $data = M('tuser_member')->find($id);
        if (!$data) {
            $this->ajaxMsg(false, '用户不存在!');
        }
        $this->assign('data', $data);
        $this->display();
    }

    /**
     * 保存项目
     */
    public function admin_recharge_save() {
        if (!$this->isSuperAdmin) {
            die('没有权限!');
        }
        $amount = I('amount');
        $siteID = I('siteID');
        $params = new \Org\Su\Params();
        $params->addParam('siteID', 'number', '用户账户无效!');
        $params->addParam('amount', 'double', '充值金额必须填写!');
        $params->addParam('origin', 'require', '充值来源必须选择!');
        if ($params->hasError()) {
            $this->ajaxMsg(false, $params->getError());
        }
        $origin = I('origin');
        $remark = I('remark');
        $params->clearParams();
        $params->addData('pflt_amount', $amount);
        $params->addData('pint_siteID', $siteID);
        $params->addData('pstr_origin', $origin);
        $params->addData('pstr_remark', $remark);
        $result = $params->query_procedure('proc_recharge');
        $result = mysql_fetch_array($result);
        $result = ($result && $result['vint_errno'] == '0') ? true : false;
        BaseController::add_user_event_log('充值', "充值{%}, 租户ID:$siteID, 金额: $amount, 支付方式: $origin", $result);
        if ($result) {
            M()->clear_table_caching(array('tuser_member', 'tfinance_recharge'));
            $this->ajaxMsg(true, '充值成功');
        } else {
            $this->ajaxMsg(false, '充值失败');
        }
    }

}
